//
//  HYBulletNode.m
//  SpriteKitDemo
//
//  Created by yanghaha on 16/4/24.
//  Copyright © 2016年 hillyoung. All rights reserved.
//

#import "HYBulletNode.h"
#import "PhysicsCategories.h"

@interface HYBulletNode ()

@property (assign, nonatomic) CGVector thrust;

@end

@implementation HYBulletNode

- (instancetype)init {
    if (self = [super init]) {
        SKLabelNode *dot = [SKLabelNode labelNodeWithFontNamed:@"Courier"];
        dot.fontColor = [SKColor blackColor];
        dot.fontSize = 40;
        dot.text = @".";
        [self addChild:dot];

        SKPhysicsBody *body = [SKPhysicsBody bodyWithCircleOfRadius:1];
        body.dynamic = YES;
        body.categoryBitMask = PlayerMissleCategory;
        body.contactTestBitMask = EnemyCategory;
        body.collisionBitMask = EnemyCategory;
        body.mass = 0.01;

        self.physicsBody = body;
        self.name = [NSString stringWithFormat:@"Bullet %p", self];
    }

    return self;
}

#pragma mark - Message

+ (instancetype)bulletFrom:(CGPoint)start toward:(CGPoint)destination {
    HYBulletNode *bullet = [[self alloc] init];
    bullet.position = start;

    CGVector movement = HYVectorBetweenPoints(start, destination);
    CGFloat magnitude = HYVectorLength(movement);
    if (magnitude == 0.0f) return nil;

    CGVector scaledMovement = HYVectorMultiply(movement, 1/magnitude);
    CGFloat thrustMagnitude = 100;
    bullet.thrust = HYVectorMultiply(scaledMovement, thrustMagnitude);

    return bullet;
}

- (void)applyRecurringForce {
    [self.physicsBody applyForce:self.thrust];
}

@end
